const http = require('../../../../utils/http.js')
const Base64 = require('../../../../utils/base64.js')
const app = getApp()
Page({

  /** pay_config.signType
   * 页面的初始数据
   */
  data: {
    imgUrl: http.imgUrl,
    navBar: {
      title: '支付确认',
      btn: 'goBack'
    },
    orderMoney: true,
    data: [],
    showPayPwdInput: false,  //是否展示密码输入层
    pwdVal: '',  //输入的密码
    payFocus: true, //文本框焦点
    lucky:2
  },

  /**
   * 返回
   */
  goBack() {
    http.goBack()
  },
  // * 显示支付密码输入层
  //  */
  // showInputLayer: function () {

  //   this.setData({ showPayPwdInput: true, payFocus: true });

  // },
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {

    var val = this.data.pwdVal;
    var is_set = this.data.is_set
    this.setData({ showPayPwdInput: false, payFocus: false, pwdVal: val, orderMoney: true, }, function () {
      if (is_set === '1') {
        wx.navigateTo({
          url: '/pages/account/center/payPassword/payPassword',
        })
      }
    });

  },
  hidePayLayers: function () {
    var val = this.data.pwdVal;
    var is_set = this.data.is_set
    console.log(is_set)
    var lucky = this.data.lucky
    var id = this.data.id
    var id_str = this.data.id_str
    var aid = this.data.aid
    this.setData({ showPayPwdInput: false, payFocus: false, pwdVal: val, orderMoney: true, }, function () {
      if (is_set === '2') {
        wx.navigateTo({
          url: '/pages/account/center/payPassword/payPassword?lucky=' + lucky + "&id=" + id + "&id_str=" + id_str + "&aid=" + aid,
        })
      }
    });
  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    console.log(e)
    this.setData({ pwdVal: e.detail.value });
    
    if (e.detail.value.length >= 6) {
      console.log(e.detail.value)
     
      this.hidePayLayer();
      this.luck() //输入完密码后的方法调用
      this.setData({ pwdVal: '' });
    }
  },



  /**
   * 立即购买
   */
  goPay() {
    let that = this,
      is_address = that.data.address,
      balance = that.data.balance,
      url = 'Order_putOrder',
      id = that.data.id,
      id_str = that.data.id_str,
      aid = that.data.aid,
      token = wx.getStorageSync('token')
      var luck = that.data.order_no
      console.log(luck)
      // var zfPrice = that.data.payModadl
      console.log(balance)
      console.log(is_address)
      console.log(that.data)
      console.log(aid)
      // console.log(order_no)
      // console.log(zfPrice)
    if (is_address) {
      if(!luck){
        http._post(
          url, { token: token, id: id, id_str: id_str, aid: aid },
          res => {
            console.log(res.data)

            let data = res.data,
              price = Base64.CusBASE64.decoder(data.data.total_fee).replace("UNO", "").replace("HACHA", ""),
              order_no = Base64.CusBASE64.decoder(data.data.order_no).replace("UNO", "").replace("HACHA", "")
            if (data.re === '1') {
              that.setData({
                payModal: {
                  show: true,
                  price: price,
                  noBalance: balance >= Number(price) ? false : true,
                  hide: 'hidePay',
                  payWay: balance >= Number(price) ? '3' : '5',
                  choosePayWay: 'choosePayWay',
                  pay: 'pay'
                },
                order_no: order_no,
                pay_price: price,
                payway: balance >= Number(price) ? '3' : '5',
                data: data
              })
            } else {
              wx.showToast({
                title: data.info,
                icon: 'none',
                duration: 3000
              })
            }
          },
          err => {
            console.log(err)
          }
        )
      }else{
        // that.setData({
        //   payModal: {
        //     show: true,
          
        //     hide: 'hidePay',
            
        //     choosePayWay: 'choosePayWay',
        //     pay: 'pay'
        //   },
        // })
        that.pay();
      }
      
    } else {
      wx.showToast({
        title: '请先设置默认地址',
        icon: 'none',
        duration: 1000
      })
    }
  },

  /**
   * 关闭立即购买
   */
  hidePay() {
    this.setData({
      payModal: {
        show: false
      }
    })
  },
  //关闭对话框
  modelHide() {
    this.setData({
      tipsModal: {
        show: false,
      }
    })
  },
  delInfoConfirm() {
    var lucky = this.data.lucky
    var id = this.data.id
    var id_str = this.data.id_str
    var aid = this.data.aid
    wx.navigateTo({
      url: '/pages/account/center/payPassword/payPassword?lucky=' + lucky + "&id=" + id + "&id_str=" + id_str + "&aid=" + aid,
    })
  },

  /**
   * 支付接口
   */
  luck() {
    var that = this
    console.log("请求支付接口")
    var url = 'Order_payOrder'
    var order_no = this.data.order_no
    var payway = this.data.payway
    var token = wx.getStorageSync('token')
    var title = this.data.pwdVal
    var order_no = this.data.order_no
    console.log(order_no)
    console.log(title)
    var pay_password = Base64.CusBASE64.encoder('UNO' + title + 'HACHA')
    console.log(pay_password)
    if(title>5){
      http._post(
        url,
        { token: token, order_no: order_no, type: payway, pay_password: pay_password },
        res => {
          var data = res.data
           console.log(data)
          console.log(order_no)
          wx.showToast({
            title: '支付成功',
            icon: "none",
            duration: 3000,
            success: function () {
              wx.navigateTo({
                url: '/pages/course/soiDetail/soiDetailPay/soiDetailPaySuc/soiDetailPaySuc'
              })
            }
          })
        }
      )
    }else{

    }
  },

  /**
   * 支付方法
   */
  pay() {
    var payway = this.data.payway
    var token = wx.getStorageSync('token')
    console.log(payway)
    console.log(token)
    // 余额支付
    if (payway === "3") {
      var url = 'Order_setMoney'
      http._post(
        url,
        { token: token },
        res => {
          var data = res.data
          console.log(data)
          var is_set = data.data.is_set
          var that = this
          if (data.data.is_set === '1') {
            that.setData({
              payModal: {
                show: false,
                pay: 'pay'
              }
            })
            that.setData({
              tipsModal: {
                show: true,
                txt: '请设置支付密码支付',
                cancel: 'modelHide',
                ok: 'delInfoConfirm',
              },
              is_set: is_set
            })
          }else{
            that.setData({
              showPayPwdInput: true,
              payFocus: true,
              orderMoney: false,
              payModal: {
                show: false,
                pay: 'pay'
              },
              is_set: is_set
            })
          } 
          // 成功输入完密码后，调用此方法
          // if (e.detail.value.length >= 6) {
          //   this.luck() //输入完密码后的方法调用
          // }
          that.luck();
        },
        err => {
          console.log(miss)
        }
      )
    }
    //余额支付

    //微信支付
    if (payway === '5') {
      var that = this
      var url = 'Order_payOrder'
      console.log(that.data.info.total_fee)
      var total_fee = that.data.info.total_fee
      var token = wx.getStorageSync('token')
      console.log(token)
      var order_no = that.data.order_no
      console.log(order_no)
      var payway = that.data.payway
      console.log(payway)
      wx.login({
        success: function (res) {
          var code = res.code
          console.log(code)

          //请求支付
          http._post(
            url,
            { token: token, order_no: order_no, type: payway, code: code },
            res => {
              var data = res.data
              console.log(data)
              //判断是否为1
              if (data.re === '1') {
                //  var rinfo = data.data.rinfo
                //  console.log(data.data.rinfo)
                var total_fee = that.data.info.total_fee
                console.log(total_fee)
                let pay_config = data.data.rinfo.jsApiParameters
                console.log(pay_config)

                //调用微信支付接口
                wx.requestPayment({
                  appId: pay_config.appId,
                  timeStamp: pay_config.timeStamp,
                  nonceStr: pay_config.nonceStr,
                  package: pay_config.package,
                  signType: "MD5",
                  paySign: pay_config.paySign,    //签名算法
                  success: function (res) {
                    console.log(res)
                    wx.navigateTo({
                      url: '/pages/course/soiDetail/soiDetailPay/soiDetailPaySuc/soiDetailPaySuc'
                    })
                  },
                  fail: function (res) {
                    console.log(res)
                    wx.showToast({
                      title: '用户取消支付',
                      icon: 'none',
                      duration: 3000,
                      success: function () {
                        that.hidePay()
                      }
                    })
                  }
                }) //微信支付接口调用完毕
              }//判断是否为1
            }
          )//请求支付
        }
      })
    }
    //微信支付
  },


  // pay() {
  //   //第一个{}号
  //   let that = this,
  //     url = 'Order_payOrder',
  //     token = wx.getStorageSync('token'),
  //     order_no = that.data.order_no,
  //     payway = that.data.payway;
  //   var beforeBalance = that.data.price //获取这个课程的价格
  //   var total_fee = that.data.info.total_fee
  //   var balance = that.data.balance;
  //   var lastBalance = balance - beforeBalance;
  //   that.setData({
  //     balance: lastBalance,
  //   })
  //   // console.log(token)
  //   // console.log(order_no)
  //   // console.log(payway)
  //   console.log(total_fee)
  //   // console.log(beforeBalance)  //课程价格
  //   // console.log(balance)
  //   // console.log(lastBalance)
  //   wx.login({
  //     //第一个({})括号
  //     success: function (res) {
  //       //第二个{}括号
  //       let code = res.code
  //       console.log(res)
  //       http._post(
  //         //第一个()括号
  //         url, { token: token, order_no: order_no, type: payway, code: code},
  //         res => {

  //             //第三个{}括号
  //           let data = res.data
  //           console.log(data)

  //           if (data.re === '1') {

  //             //第四个{}括号
  //             that.setData({
  //               balance: lastBalance
  //             })
  //             // if(payway==='3'){
  //             //   console.log(333)
  //             // }

  //               if (payway === '2') {
  //                 var total_fee = that.data.info.total_fee
  //                 console.log(total_fee)
  //                 //第五个{}括号
  //                 // let pay_config = data.data.rinfo.jsApiParameters
  //                 let pay_config = data.data.rinfo
  //                 console.log(pay_config)
  //                 wx.requestPayment({
  //                   //第二个({})括号
  //                   appId: pay_config.appid,
  //                   timeStamp: pay_config.timestamp,
  //                   nonceStr: pay_config.noncestr,
  //                   package: "prepay_id="+pay_config.package+"",
  //                   signType: "MD5",
  //                   paySign: pay_config.sign,    //签名算法
  //                   success: function (res) {
  //                     console.log(res)
  //                     // wx.navigateTo({
  //                     //   url: '/pages/course/paySuc/paySuc?id=' + that.data.id,
  //                     // })
  //                   },
  //                   fail: function (res) {
  //                     console.log(res)
  //                     wx.showToast({
  //                       title: '用户取消支付',
  //                       icon: 'none',
  //                       duration: 3000,
  //                       success: function () {
  //                         that.hidePay()
  //                       }
  //                     })
  //                   }
  //                 })//第二个({})括号毕
  //               }//第五个{}括号毕                 
  //               else if(payway ==='3') {                
  //                 wx.showToast({
  //                   title: "qqq",
  //                   icon: 'none',
  //                   duration: 1500,
  //                   success: function () {
  //                     setTimeout(function () {
  //                       wx.navigateTo({
  //                         // url: '/pages/course/paySuc/paySuc?id=' + that.data.id,
  //                       })
  //                     }, 1500)
  //                   }
  //                 })
  //               }
  //           //第四个{}括号毕 
  //           }else {
  //             wx.showToast({
  //               title: "999",
  //               icon: 'none',
  //               duration: 3000,
  //               success: function () {
  //                 that.hidePay()
  //               }
  //             })
  //           }
  //         },//第三个{}括号毕
  //         err => {
  //           console.log(err)
  //         }

  //       )//第一个()括号毕
  //     }//第二个{}括号毕
  //   })//第一个({})括号毕
  //   that.setData({
  //     balance: lastBalance
  //   })
  // },//第一个{}括号毕

  /**
   * 选择支付方式
   */
  choosePayWay(e) {
    console.log(e)
    let that = this,
      price = that.data.pay_price,
      balance = that.data.balance,
      payway = e.currentTarget.dataset.payway
    if (balance > Number(price)) {
      that.setData({
        payModal: {
          show: true,
          price: price,
          noBalance: false,
          hide: 'hidePay',
          payWay: payway,
          choosePayWay: 'choosePayWay',
          pay: 'pay'
        },
        payway: payway
      })
      // console.log(22)
    }
    console.log(payway)
  },

  /**
   * 选择教辅资料
   */
  chooseTm(e) {
    let that = this,
      index = http.dataIndex(e)[0],
      id = http.dataIndex(e)[1],
      chosenTmList = that.data.chosenTmList,
      id_str = that.data.id_str,
      temp_arr = id_str === '' ? [] : id_str.split(','),
      in_where = temp_arr.indexOf(id)

    if (chosenTmList[index]) {
      chosenTmList[index] = false
      temp_arr.splice(in_where, 1)
    } else {
      chosenTmList[index] = true
      temp_arr.push(id)
    }

    let temp_str = temp_arr.join(',')
    that.setData({
      chosenTmList: that.data.chosenTmList,
      id_str: temp_str
    })

    let url = 'Order_orderTrue',
      id_1 = that.data.id,
      aid = that.data.aid,
      token = wx.getStorageSync('token')

    http._post(
      url, { id: id_1, id_str: temp_str, aid: aid },
      res => {
        let data = res.data
        if (data.re === '1') {
          that.setData({
            info: data.data
          })
        } else {
          that.setData({
            info: {}
          })
        }
      },
      err => {
        console.log(err)
      }
    )
  },

  /**
   * 到更换/选择地址
   */
  goAddress() {
    wx.navigateTo({
      url: '/pages/account/address/address?from=1',
    })
  },
  chooseTmBtn() {
    wx.showToast({
      title: '抱歉！捆绑销售，无法取消',
      icon: 'none',
      duration: 1000
    })
  },
  /**
   * 获取页面基本信息
   */
  getInfo() {
    let that = this,
      url = 'Order_orderTrue',
      id = that.data.id,
      id_str = that.data.id_str,
      aid = wx.getStorageSync('aid') || 0,
      token = wx.getStorageSync('token')
    http._post(
      url, { id: id, id_str: id_str, aid: aid },
      res => {
        console.log(res.data)

        let data = res.data
        if (data.re === '1') {
          let temp_chosenTmList = []
          for (let item of data.data.otherList) {
            temp_chosenTmList.push(true)
          }
          console.log(data.data.total_price)
          that.setData({
            info: data.data,
            otherList: data.data.otherList,
            chosenTmList: temp_chosenTmList,
            address: data.data.address_list,
            aid: data.data.address_list.address_id,
            price: data.data.total_price
          })
        } else {
          that.setData({
            info: {}
          })
        }
      },
      err => {
        console.log(err)
      }
    )
  },

  /**
   * 获取默认收货地址
   */

  /**
   * 获取余额
   */
  getBalance() {
    let that = this,
      url = 'Ucenter_userMoney',
      token = wx.getStorageSync('token')

    http._post(
      url, { token: token },
      res => {
        console.log(res.data)
        let data = res.data
        if (data.re === '1') {
          that.setData({
            balance: Number(data.data)
          })
        } else {
          that.setData({
            balance: lastBalance
          })
          console.log(balance)
        }
      },
      err => {
        console.log(err)
      }
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this

    that.setData({
      id: options.id || '0',
      id_str: options.id_str || '',
      aid: options.aid || '0',
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    var back = app.globalData.back
    if (back) {
      console.log(back)
      that.setData({
        id: back.cid,
        id_str: back.id_str,
        aid: back.aid,
      })
      app.globalData.back = ""
    }
    setTimeout(() => {
      this.getBalance() // 获取余额
      setTimeout(() => {
        this.getInfo() // 获取页面基本信息
      }, 100)
    }, 100)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})